<template>
  <div class="changeAddress">
    <header>
      <div class="left" @click="$router.back()"></div>
      <p>{{ $route.query.id ? "新建地址" : "编辑地址" }}</p>
    </header>

    <div class="content">
      <van-address-edit
        :area-list="areaList"
        :address-info="addressInfo"
        show-set-default
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave"
      />
    </div>
  </div>
</template>

<script>
// npm i @vant/area-data
import { areaList } from "@vant/area-data";
export default {
  data() {
    return {
      areaList,
      addressInfo: {},
      userInfo: null,
    };
  },
  methods: {
    // 保存
    onSave(content) {
      this.$toast("已保存");

      let user = localStorage.getItem("HL_user");
      let index = this.userInfo[user].address.findIndex(
        (vl) => vl.id == this.$route.query.id
      );

      if (index != -1) {
        this.userInfo[user].address[index] = content;

        console.log(this.userInfo[user].address[index]);

        this.setItem("userInfo", this.userInfo);
      } else {
        let length = this.userInfo[user].address.length;

        let id = this.userInfo[user].address[length - 1].id + 1;

        this.userInfo[user].address.push({ id, ...content });

        this.setItem("userInfo", this.userInfo);
      }
    },
    // 获取用户数据
    getUserInfoFun() {
      let user = localStorage.getItem("HL_user");
      this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      let index = this.userInfo[user].address.findIndex(
        (vl) => vl.id == this.$route.query.id
      );

      if (index != -1) {
        this.addressInfo = this.userInfo[user].address[index];
      }
    },
    // 修改数据
    setItem(item, newItem) {
      sessionStorage.setItem(item, JSON.stringify(newItem));
    },
  },
  created() {
    this.$emit("hide");
    this.getUserInfoFun();
  },
};
</script>

<style lang="scss" scoped>
.changeAddress {
  position: relative;

  > .content {
    > .van-address-edit::v-deep .van-address-edit__buttons {
      height: 44px;
      width: 100%;
      line-height: 44px;
      position: fixed;
      left: 0;
      bottom: 0;
      padding: 0;
      font-size: 14px;
      color: #fff;
      background: #cb3340;
      text-align: center;

      .van-button {
        background: #cb3340;
      }
    }
  }
}
</style>